package afcp.alumni.action.event;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.EventAction;
import afcp.alumni.action.page.HomeAction;
import afcp.alumni.model.db.Login;
import afcp.alumni.model.db.Member;
import afcp.alumni.security.PasswordEncoder;
import afcp.alumni.service.LoginService;
import afcp.alumni.service.MemberService;
import afcp.alumni.service.SF;

@UrlBinding(LoginAction.URL)
public class LoginAction extends EventAction {

	private static final Log logger = LogFactory.getLog(LoginAction.class);

	public static final String URL = "/login";

	@Override
	public String getUrl() {
		return URL;
	}

	@Override
	@DefaultHandler
	public Resolution view() {
		return new RedirectResolution(fromUrl());
	}

	private static LoginService loginService = SF.login();
	private static MemberService memberService = SF.member();

	@ValidateNestedProperties(
			@Validate(field="id", required = true, on = "login", minlength = 2)
	)
	private Login loginuser;
	@Validate(required = true, on = "login", minlength = 2, converter = PasswordEncoder.class)
	private String loginpassword;

	public Login getLoginuser() {
		return loginuser;
	}

	public void setLoginuser(Login loginuser) {
		this.loginuser = loginuser;
	}

	public String getLoginpassword() {
		return loginpassword;
	}

	public void setLoginpassword(String loginpassword) {
		this.loginpassword = loginpassword;
	}
	
	private Member userLoging = null;
//	private Member getUserLoging() {
//		if (userLoging == null) {
//			userLoging = loginService.findUser(loginuser);
//		}
//		return userLoging;
//	}

	// public String getUser() {
	// return (String) context.getRequest().getSession().getAttribute("user");
	// }

	@ValidationMethod(on = "login")
	public void validateUser(ValidationErrors errors) {
		userLoging = loginService.findUser(loginuser);
		boolean allowed = true;
		if (userLoging == null && MemberService.ADMIN_LOGIN.equals(loginuser.getId())) {
			logger.info("No administrator found on datastore. It seems to "
					+ "be the first administrator login. Adding a default "
					+ "administrator to the datastore and continuing login "
					+ "process...");
			userLoging = memberService.addOrUpdateNewAdminMember();
		}
		if (userLoging == null) {
			errors.addGlobalError(new LocalizableError("database.dontexist"));
			allowed = false;
		} else if (!loginpassword.equals(userLoging.getPassword())) {
			errors.addGlobalError(new LocalizableError("database.incorrectpassword"));
			allowed = false;
		}
		if (allowed) {
			logger.info("User " + userLoging.getFirstName() + " " + userLoging.getLastName() + " (" + loginuser.getId() + ") is allowed to login.");
		} else {
			logger.info("User " + loginuser.getId() + " is not allowed to login. unknown account or incorrect password.");
		}
	}
	
	public Resolution login() {
		loginService.login(userLoging, context);
//		Resolution sourcePage = this.context.getSourcePageResolution();
		return fromRedirect();
	}

	public Resolution logout() {
		loginService.logout(context);
		return new RedirectResolution(HomeAction.class);
	}
	
	private String from = null;
	
	public void setFrom(String from) {
		this.from = from;
	}

	private String fromUrl = null;
	@Override
	protected String fromUrl() {
		if (fromUrl == null) {
			if (from != null) {
				logger.info("Redirecting to source page: " + from);
				fromUrl = from;
			} else {
				logger.warn("The source page where the request come from has not been found. Can't redirect to the page where the user was when sending the login request.");
				fromUrl = HomeAction.URL;
			}
		}
		return fromUrl;
	}
}
